package sjtu.ist.ecommerce.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

public class ServiceAccessor {
	private static final String FILE_ADDR="resource\\service.xml";
	
	public Object httpGet(String name,String opt,Class<?> clazz) throws IOException{
		return httpGet(name,opt,new HashMap<String,String>(),clazz);
	}
	
	public Object httpGet(String name,String opt, Map param, Class<?> clazz) throws IOException{
		String urlStr=findService("get",name,opt,param);
		
		String urlParamStr = "?";
	    if(!param.isEmpty()){
	        //定义一个迭代器，并将MAP值的集合赋值
	        Iterator ups = param.entrySet().iterator();
	        while(ups.hasNext()){
	            Map.Entry MUPS = (Map.Entry)ups.next();
	            urlParamStr += MUPS.getKey() + "=" + MUPS.getValue().toString().trim() + "&";
	        }
	        urlParamStr = urlParamStr.substring(0, urlParamStr.length() - 1);
	    }
	    //实例一个URL资源
	    URL url = new URL(urlStr + urlParamStr);
	    //实例一个HTTP CONNECT
	    HttpURLConnection connet = (HttpURLConnection) url.openConnection();
	    if(connet.getResponseCode() != 200){
	        throw new IOException(connet.getResponseMessage());
	    }
	    //将返回的值存入到String中
	    //BufferedReader brd = new BufferedReader(new InputStreamReader(connet.getInputStream()));
	    XMLParser parser=new XMLParser();
	    Object obj=parser.unmarshal(connet.getInputStream(), clazz);
	    
	    //brd.close();
	    connet.disconnect();
	 
	    return obj;
	}
	
	public Object httpPost(String name,String opt, Map param, Class<?> clazz) throws IOException{
		String urlStr=findService("get",name,opt,param);
		
		if("".equals(urlStr)) return "0";
        String paramStr = "";
        URL url = new URL(urlStr);
        //实例一个http资源链接
        HttpURLConnection urlconn = (HttpURLConnection) url.openConnection();
        //设置链接的属性
        urlconn.setRequestMethod("POST");
        urlconn.setDoOutput(true);
        urlconn.setDoInput(true);
        urlconn.setUseCaches(false);
        urlconn.setAllowUserInteraction(false);
        urlconn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        //实例一个输出流对象
        OutputStream outs = urlconn.getOutputStream();
        //实例一个Writer，并初始化
        Writer writer = new OutputStreamWriter(outs, "UTF-8");
        if(param.size() > 0){
            Iterator ups = param.entrySet().iterator();
            while (ups.hasNext()){
                Map.Entry upskv = (Map.Entry) ups.next();
                paramStr += upskv.getKey() + "=" + URLEncoder.encode(upskv.getValue().toString().trim(), "UTF-8") + "&";
            }
            paramStr = paramStr.substring(0, paramStr.length() - 1);
        }
        //写入字符串
        writer.write(paramStr);
        //结束Writer和OutputStream
        writer.close();
        outs.close();
        //获得请求的响应状态
        if(urlconn.getResponseCode() != 200){
            throw new IOException(urlconn.getResponseMessage());
        }
        //实例一个Buffer读取和字符串Builder
//        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlconn.getInputStream()));
//        StringBuilder  stringBuilder = new StringBuilder();
//        String line;
//        //将读取到的数据装载到line当中
//        while((line = bufferedReader.readLine()) != null){
//            stringBuilder.append(line);
//        }
        XMLParser parser=new XMLParser();
	    Object obj=parser.unmarshal(urlconn.getInputStream(), clazz);        
        
        urlconn.disconnect();
        return obj;
	}
	
	private String findService(String method,String name,String operation,Map param){
		String url="";
		SAXBuilder builder = new SAXBuilder();
		Document doc=null;
		try {
			String addr=this.getClass().getClassLoader().getResource("").getPath()+"..\\..\\";
			File file=new File(addr+FILE_ADDR);
			doc=builder.build(file);
		} catch (JDOMException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		Element root=doc.getRootElement();
		//找到指定service
		List<Element> list=root.getChildren("service");
		Element svc=null;
		for(int i=0;i<list.size();i++){
			Element ele=list.get(i);
			if(ele.getAttributeValue("name").equals(name)){
				svc=ele;
				break;
			}
		}
		if(svc==null){
			return url;
		}
		
		//根据method找到指定opt
		List<Element> mlist=svc.getChildren(method);
		Element opt=null;
		for(int i=0;i<mlist.size();i++){
			Element ele=mlist.get(i);
			if(ele.getAttributeValue("operation").equals(operation)){
				opt=ele;
				url=ele.getAttributeValue("url");
				break;
			}
		}
		if(opt==null){
			return url;
		}
		
		//匹配url中的参数
		if(!param.isEmpty()){
	        //定义一个迭代器，并将MAP值的集合赋值
	        Iterator ups = param.entrySet().iterator();
	        while(ups.hasNext()){
	            Map.Entry MUPS = (Map.Entry)ups.next();
	            String urlparam="{"+MUPS.getKey().toString()+"}";
	            String regex="\\{"+MUPS.getKey().toString()+"\\}";
	            if(url.contains(urlparam)){
	            	url=url.replaceAll(regex, MUPS.getValue().toString());
	            	param.remove(MUPS.getKey());
	            }
	        }
	    }
		
		return url;
	}
}
